package com.heima.behavior.service.iml;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /*
    * 保存文章信息
    * */
    @Override
    public ResponseResult saveReadBehavior(ReadBehaviorDTO dto) {

        //1. 校验参数 文章id必须传,使用的注解
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry abeId=null;

            if (user == null) {
                abeId = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
            } else {
                abeId = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            }
        if (abeId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有对应行为实体");
        }
        Query query = Query.query(Criteria.where("entryId").is(abeId.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        //3. 判断阅读行为是否存在
        if (one == null){//5. 不存在  创建阅读行为 并初始化count字段值为 1
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(abeId.getId());
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short)1);
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }else {
            //4. 存在  将阅读行为的count字段加1 并修改
            int i = one.getCount() + 1;
            one.setCount((short) i);
            mongoTemplate.save(one);
        }
        return ResponseResult.okResult();
    }
}
